﻿@using FwProject.Settlement.Dto
@using FwProject.PrePaymentInfo.Dto
@using FwProject.PrePaymentInfo
@model ReceiptInfoEnterDto
@{
    ViewBag.Title = "新增收款单";
}
@section styles{
    <link href="~/Theme/css/plugins/iCheck/custom.css" rel="stylesheet">
    <link href="~/Theme/css/plugins/datapicker/datepicker3.css" rel="stylesheet">
}
<div class="row wrapper wrapper-content animated fadeInRight">
    <div class="col-sm-12">
        <div class="ibox float-e-margins">
            <div class="ibox-title">
                <h5>@ViewBag.Title</h5>
                <div class="ibox-tools">
                    <button type="button" class="btn btn-primary btn-xs btnSave" data-id="保存">保存</button>
                    <button type="button" class="btn btn-primary btn-xs btnSave" data-id="提交">提交</button>
                    @*<a class="btn btn-primary btn-xs" onclick="window.open('/Print/ReceiptPrint?id=@Model.Item1.Id')">打印</a>*@
                </div>
            </div>
            <div class="ibox-content" style="height:700px">
                <form class="form-horizontal" id="form" action="/Receipt/Create" data-ajax="true" data-ajax-update="#data_list" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="ReloadAjaxCallbackgoback" data-ajax-failure="FailureAjaxCallback">
                    <div class="row m-b-sm m-t-sm">
                        <input type="hidden" name="ReceiptInfoStatus" id="ReceiptInfoStatus" value="@ReceiptInfoStatus.未提交" />
                        <div class="form-group">
                            <div class="col-md-4">
                                <label class="control-label col-md-3">单号：</label>
                                <div class="input-group">
                                    <input type="text" name="ReceiptInfoNumber" class="input-sm form-control" value="系统自动生成" readonly="readonly">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">收款日期：</label>
                                <div class="input-group">
                                    <input name="Dateofreceipt" id="Dateofreceipt" value="@DateTime.Now.ToString(" yyyy-MM-dd")" class="input-sm form-control" />
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">经办人：</label>
                                <div class="input-group" style="width:162px">
                                    <input type="hidden" name="AgentPeoperUserId" id="AgentPeoperUserId" value="" />
                                    <input type="text" name="AgentPeoper" data-val="true" data-val-length="不能超过200个字符" data-val-length-max="200" data-val-required="经办人不能为空" id="dropdown-agentpeoperuserid" value="" class="form-control" onblur="blurEmpty()">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown" style="line-height:1.455;padding:6px 12px;">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu" style="z-index: 9999;"></ul>
                                    </div>
                                    <span class="field-validation-valid" data-valmsg-for="AgentPeoper" data-valmsg-replace="true"></span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-4">
                                <label class="control-label col-md-3">餐厅：</label>
                                <div class="input-group col-md-5" style="padding:0;">
                                    @Html.TextBoxFor(o => o.RestaurantId, new { @class = "hidden" })
                                    <input type="text" id="dropdown-restaurant" value="" class="form-control">
                                    <div class="input-group-btn">
                                        <button type="button" class="btn btn-white dropdown-toggle" data-toggle="dropdown" style="line-height:1.455;padding:6px 12px;">
                                            <span class="caret"></span>
                                        </button>
                                        <ul class="dropdown-menu dropdown-menu-right" role="menu" style="z-index: 9999;"></ul>
                                    </div>
                                    @Html.ValidationMessageFor(o => o.RestaurantId)
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">预收款余额：</label>
                                <div class="input-group">
                                    @Html.TextBoxFor(o => o.UsePrePaymentSurplus, new { @class = "input-sm form-control", @readonly = "readonly" })
                                    @Html.ValidationMessageFor(o => o.UsePrePaymentSurplus)
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">使用预收款：</label>
                                <div class="input-group">
                                    @Html.TextBoxFor(o => o.UsePrePayment, new { @class = "input-sm form-control", onkeyup = "setGloabPrice(this)" })
                                    @Html.ValidationMessageFor(o => o.UsePrePayment)
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-4">
                                <label class="control-label col-md-3">收款账户：</label>
                                <div class="input-group">
                                    @Html.DropDownListFor(o => o.CapitalAccountId, ViewBag.Account as IEnumerable<SelectListItem>
                                        , new { @class = "input-sm form-control" })
                                    @Html.ValidationMessageFor(o => o.CapitalAccountId)
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="control-label col-md-3">收款金额：</label>
                                <div class="input-group">
                                    @Html.TextBoxFor(o => o.TaskBackAmount, new { @class = "input-sm form-control", @readonly = "readonly" })
                                    <span style="color:red" id="sumPre">总未收金额：(0.00)</span>
                                    @Html.ValidationMessageFor(o => o.TaskBackAmount)
                                </div>
                            </div>
                            @*<div class="col-md-4">
                                    <label class="control-label col-md-3">本次收回预收款：</label>
                                    <div class="input-group">
                                        @Html.TextBoxFor(o => o.ActualAmount, new { @class = "input-sm form-control" })
                                        @Html.ValidationMessageFor(o => o.TaskBackAmount)
                                    </div>
                                </div>*@
                        </div>
                        <div class="form-group">
                            <div class="col-md-12">
                                <label class="control-label col-md-3" style="width:132px">备注：</label>
                                <div class="input-group col-md-9">
                                    @Html.TextAreaFor(o => o.RemarksConten, new { @class = "input-sm form-control" })
                                </div>
                            </div>
                        </div>

                    </div>
                    <div class="ibox-title">
                        <button type="button" class="btn btn-primary btn" id="selectSettlement">选择应收单据</button>
                    </div>
                    <div id="data_list">
                        <div>
                            <table class="table table-bordered table-hover table-rowselected">
                                <thead>
                                    <tr>
                                        <th>单据类型</th>
                                        <th>单据编号</th>
                                        <th>单据日期</th>
                                        <th>配送日期</th>
                                        <th>应收金额</th>
                                        <th>未收金额</th>
                                        <th>本次收款金额</th>
                                        <th>收款优惠</th>
                                        <th>备注</th>
                                    </tr>
                                </thead>
                                <tbody id="list_tbody"></tbody>
                            </table>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<div id="modal_ajax" class="modal inmodal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
</div>
<div id="model_selectSettlement" class="modal inmodal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"></div>
@section scripts{
    <script src="~/Theme/js/content.min.js?v=1.0.0"></script>
    <script src="~/Theme/js/plugins/iCheck/icheck.min.js"></script>
    <script src="~/Theme/js/plugins/datapicker/bootstrap-datepicker.js"></script>
    <script src="~/Theme/js/plugins/suggest/bootstrap-suggest2014.js"></script>
    <script src="~/js/DateComm.js"></script>
    <script>
        var usePrePaymentSurplus = 0;
        var sumUncollected = 0;
        $(document).ready(function () {
            $('#Dateofreceipt').datepicker();
            $.getJSON("/Deposit/GetAgentPeoperData").done(function (data) {
                CommonAjaxCallback(data, function () {
                    bindSuggest(data.result);
                }, null);
            }).fail(function () {
                layer.msg('连接超时，获取经办人失败！', {
                    icon: 2,
                    time: 2000
                });
            });
            $.getJSON("/Restaurant/GetRestaurantAdvancePaymentData").done(function (data) {
                CommonAjaxCallback(data, function () {
                    bindRestaurantSuggest(data.result);
                }, null);
            }).fail(function () {
                layer.msg('连接超时，获取餐厅失败！', {
                    icon: 2,
                    time: 2000
                });
            });



            $('#modal_ajax').on('show.bs.modal', function (e) {
                $(this).addClass('loading');
                var $button = $(e.relatedTarget);
                var url = $button.data('url');
                if (!!url) {
                    url = url + ((url.indexOf("?") > -1) ? "&r=" : "?r=") + Math.random();
                    $(this).load(url, function () {
                        $.validator.unobtrusive.parse(this); //$("#form_model_create").validate();
                        $("input[name='CarOld']").datepicker({ todayBtn: "linked", keyboardNavigation: !1, forceParse: !1, calendarWeeks: !0, autoclose: !0 });
                        $(".i-checks").iCheck({ checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green", });
                        $(this).removeClass('loading');
                    });
                }
            });
            $('#modal_ajax').on('hidden.bs.modal', function (e) {
                $(this).empty();
            });

            $('.btnSave').click(function () {
                if ($("#AgentPeoperUserId").val()=="") {
                    layer.msg("请选择经办人");
                    return false;
                }
                var trs = $("#list_tbody").find("tr");
                if (trs.length==0) {
                    layer.msg("请选择收款收据");
                    return false;
                }

                var btn = $(this).data("id");
                if (btn=="保存") {
                    $('#ReceiptInfoStatus').val("未提交");
                } else if(btn=="提交") {
                    $('#ReceiptInfoStatus').val("已提交");
                }
                $('#form').submit();
            });



            $('#UsePrePayment').on('input', function () {
                var usePrePayment = 0.00;
                if (isNaN($('#UsePrePayment').val()) || $('#UsePrePayment').val() == "") {
                    $('#UsePrePayment').val(usePrePayment);
                } {
                    usePrePayment = parseFloat($('#UsePrePayment').val());
                }

                if (sumUncollected < usePrePayment) {
                    layer.msg("使用预收款不能大于总未收金额");
                    $('#UsePrePayment').val(0.00);
                    return false;
                }

                if (usePrePaymentSurplus < usePrePayment) {
                    layer.msg("使用预收款不能大于预收款余额");
                    $('#UsePrePayment').val(0.00);
                    return false;
                }

                var taskBackAmount = 0;
                var ys = $("#list_tbody").find("input[data-name='receipt']");
                if (ys.length!=0) {
                    for (var i = 0; i < ys.length; i++) {
                        taskBackAmount += parseFloat($(ys[i]).val());
                    }
                }

                $('#TaskBackAmount').val(toFloat(taskBackAmount - usePrePayment));
                $("#UsePrePaymentSurplus").val(toFloat(usePrePaymentSurplus - usePrePayment));
            });

            $('#selectSettlement').on('click', function () {
                if ($('#RestaurantId').val() == "@Guid.Empty" || $('#RestaurantId').val() =="") {
                    layer.msg('请先选择餐厅！');
                    return false
                }
                layer.load();
                $('#model_selectSettlement').load("/Receipt/SelectSettlement?id=" + $('#RestaurantId').val(), function () {
                    $(".i-checks").iCheck({ checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green", });
                    $('#chkDiv').on('ifChecked', function (event) { //ifCreated 事件应该在插件初始化之前绑定
                        $("#t tbody").find('.i-checks').iCheck('check');
                    });
                    $('#chkDiv').on(' ifUnchecked', function (event) { //ifCreated 事件应该在插件初始化之前绑定
                        $("#t tbody").find('.i-checks').iCheck('uncheck');
                    });

                    $("#save").on("click", function () {
                        var t = $("#t tbody").find('input[type="checkbox"]');
                        var total=0;
                        for (var i = 0; i < t.length; i++) {
                            if ($(t[i]).prop('checked')) {
                                if ($("#list_tbody").find("tr[data-id='" + $(t[i]).val()+"']").length==0) {
                                var balanceWay = $(t[i]).parent().parent().parent().parent().find("input[name='BalanceWayEnum']").val();
                                var creationNumber = $(t[i]).parent().parent().parent().parent().find("input[name='CreationNumber']").val();
                                var creationTime = $(t[i]).parent().parent().parent().parent().find("input[name='CreationTime']").val();
                                var deliveryDate = $(t[i]).parent().parent().parent().parent().find("input[name='DeliveryDate']").val();
                                var actualprice = $(t[i]).parent().parent().parent().parent().find("input[name='Actualprice']").val();
                                var uncollected = $(t[i]).parent().parent().parent().parent().find("input[name='Uncollected']").val();
                                var remarks = $(t[i]).parent().parent().parent().parent().find("input[name='RemarksConten']").val();


                                var tr = $('<tr data-id="' + $(t[i]).val()+'">');
                                    tr.append('<td><input name="Settlements[' + i + '].SettlementId" type="hidden" value="' + $(t[i]).val() + '" />' + balanceWay + '</td>');

                                tr.append('<td>' + creationNumber + '</td>');
                                tr.append('<td>' + creationTime + '</td>');
                                tr.append('<td>' + deliveryDate + '</td>');
                                tr.append('<td>' + actualprice + '</td>');
                                tr.append('<td><input  name="Settlements[' + i +'].uncollected" data-name="uncollected" type="hidden" value="' + uncollected +'" />' + uncollected + '</td>');

                                tr.append('<td><input name="Settlements[' + i + '].receipt" data-name="receipt" onkeyup="skPirce(this)" type="text" value="' + uncollected + '" class="form-control" /></td>');
                                    if (parseFloat(uncollected)>=0) {
                                        tr.append('<td><input name="Settlements[' + i + '].offer" data-name="offer" onkeyup="yhPirce(this)" type="text" value="0.00" class="form-control"/></td>');
                                    } else {
                                        tr.append('<td><input name="Settlements[' + i + '].offer" data-name="offer" onkeyup="yhPirce(this)" readonly="readonly" type="text" value="0.00" class="form-control"/></td>');
                                    }

                                tr.append('<td><input name="Settlements[' + i + '].Remarks" type="text" value="' + remarks+'" class="form-control"/></td>');

                                    sumUncollected += parseFloat(uncollected);

                                    $("#sumPre").text("总未收金额：(" + toFloat(sumUncollected) + ")");

                                $("#data_list").find("tbody").append(tr);

                                }
                            }
                        }
                        $('#TaskBackAmount').val(toFloat(sumUncollected));
                        $('#model_selectSettlement').modal('hide');
                    })


                    layer.closeAll('loading');
                    $('#model_selectSettlement').modal('show');
                })

            })

            $('#model_selectSettlement').on('hidden.bs.modal', function (e) {

                $(this).empty();
            });
        });

        function skPirce(obj) {
            var receipt=0;
            if (isNaN($(obj).val()) || $(obj).val() == "") {
                if ($(obj).val().charAt(0) == '-') {
                    receipt = parseFloat($(obj).val());
                } else {

                    $(obj).val(0.00);
                }

            } else {
                receipt = parseFloat($(obj).val());
            }
            var tr = $(obj).parent().parent();
            var uncollected = parseFloat(tr.find("input[data-name='uncollected']").val());
            var offer = parseFloat($(tr).find("input[data-name='offer']").val());
            var receipt = parseFloat($(tr).find("input[data-name='receipt']").val());
            //$(tr).find("input[data-name='offer']").val(toFloat(uncollected - receipt));

            if (uncollected < receipt + offer) {
                layer.msg("优惠加收款不能大于应收金额");
                if (uncollected > offer) {
                    receipt = uncollected - offer;
                    $(obj).val(receipt);
                } else {
                    receipt = uncollected;
                    $(obj).val(receipt);
                    $(tr).find("input[data-name='offer']").val(0.00);
                }
                //if (receipt > uncollected) {
                //    receipt = uncollected;
                //    $(obj).val(receipt);
                //    $(tr).find("input[data-name='offer']").val(0.00);
                // } else {

                //    $(tr).find("input[data-name='offer']").val(uncollected - receipt);
                // }
             }
            setGloabPrice();


        }

        function setGloabPrice() {
            //总收
            var total = 0;

            var res = $("#list_tbody").find("input[data-name='receipt']");
            for (var i = 0; i < res.length; i++) {
                total += parseFloat($(res[i]).val());
            }

            //总应收
            var uncollected = 0;
            var res = $("#list_tbody").find("input[data-name='uncollected']");
            for (var i = 0; i < res.length; i++) {
                uncollected += parseFloat($(res[i]).val());
            }
            //总优惠
            var offer = 0;
            var res = $("#list_tbody").find("input[data-name='offer']");
            for (var i = 0; i < res.length; i++) {
                offer += parseFloat($(res[i]).val());
            }
            var UsePrePaymentSurplus = parseFloat($("#UsePrePaymentSurplus").val());

            var UsePrePayment = parseFloat($('#UsePrePayment').val());

            if (uncollected >0) {
                //不够填充的资金
               var k=  uncollected - total - offer;
                if (UsePrePaymentSurplus > k) {
                    $('#UsePrePayment').val(k);
                } else {
                    $('#UsePrePayment').val(UsePrePaymentSurplus);
                }
            } else {
                $('#UsePrePayment').val(0.00);
            }
            //if (total + offer + UsePrePayment < uncollected)
            //      layer.msg("实际应收有误请修改数据");

              $('#TaskBackAmount').val(toFloat(total));
        }


        function yhPirce(obj) {
            var offer = 0;
            if (isNaN($(obj).val()) || $(obj).val() == "") {
                if ($(obj).val().charAt(0) == '-') {
                    offer = parseFloat($(obj).val());
                } else {

                    $(obj).val(0.00);
                }
            } else {
                offer = parseFloat($(obj).val());
            }
            var tr = $(obj).parent().parent();
            var uncollected = parseFloat(tr.find("input[data-name='uncollected']").val());
            var receipt = parseFloat($(tr).find("input[data-name='receipt']").val());
            var offer = parseFloat($(tr).find("input[data-name='offer']").val());
            //$(tr).find("input[data-name='receipt']").val(toFloat(uncollected - offer));

            if (uncollected<0) {
                $(obj).val(0.00);
            }
            else if (uncollected < receipt + offer) {
                layer.msg("优惠加收款不能大于应收金额");
                if (receipt > uncollected) {
                    receipt = uncollected;
                    $(obj).val(0.00);
                    $(tr).find("input[data-name='receipt']").val(receipt);
                } else {

                    $(obj).val(uncollected - receipt);
                 }
            }
            setGloabPrice();

        }




        function bindSuggest(data) {
            if ($("#dropdown-agentpeoperuserid") != undefined) {
                $role = $("#dropdown-agentpeoperuserid").bsSuggest({
                    effectiveFields: ["name"],
                    effectiveFieldsAlias: { "name": "姓名" },
                    searchFields: ["name"],
                    clearable: true,
                    getDataMethod: "data",
                    callfun:function() {
                        $("#AgentPeoperUserId").val("");
                    },
                    //url: "/Users/GetSuggestData?type=司机类型&keyword=",
                    data: { value: data },
                    idField: "id",
                    keyField: "name",
                }).on('onDataRequestSuccess', function (e, result) {
                    console.log('onDataRequestSuccess: ', result);
                }).on('onSetSelectValue', function (e, keyword, data) {
                    $("#AgentPeoperUserId").val(data.id);
                    console.log('onSetSelectValue: ', keyword, data);
                }).on('onUnsetSelectValue', function () {
                    console.log('onUnsetSelectValue');
                });
            }
        }

        function bindRestaurantSuggest(data) {
            if ($("#dropdown-restaurant") != undefined) {
                $role = $("#dropdown-restaurant").bsSuggest({
                    effectiveFields: ["restaurantName","advancePayment"],
                    effectiveFieldsAlias: { "restaurantName": "餐厅名称","advancePayment":"预收款余额"},
                    searchFields: ["restaurantName"],
                    clearable: true,
                    getDataMethod: "data",
                    callfun: function () {
                        $("#RestaurantId").val("");
                    },
                    data: { value: data },
                    idField: "id",
                    keyField: "restaurantName",
                }).on('onDataRequestSuccess', function (e, result) {
                    console.log('onDataRequestSuccess: ', result);
                }).on('onSetSelectValue', function (e, keyword, data) {
                    $("#RestaurantId").val(data.id);
                    $("#UsePrePaymentSurplus").val(data.advancePayment);
                    $("#UsePrePayment").val(0);
                    $("#TaskBackAmount").val(0);
                    $("#list_tbody").empty();

                    usePrePaymentSurplus = data.advancePayment;
                    console.log('onSetSelectValue: ', keyword, data);
                }).on('onUnsetSelectValue', function () {
                    console.log('onUnsetSelectValue');
                });
            }

        }


        function blurEmpty() {
            var cityObj = $("#dropdown-agentpeoperuserid");
            var DriverId = $("#AgentPeoperUserId");
            if (cityObj.val() == "") {
                DriverId.attr("value", "");
            }
        }

        function setPrice(obj) {
            var TotalPrice = $('#TotalPrice').val();
            var Actualprice = $('#Actualprice').val();
            var ReceivedDiscount = $('#ReceivedDiscount').val();
            if (ReceivedDiscount > TotalPrice) {
                $('#ReceivedDiscount').val(0);
            } else {
                $('#Actualprice').val(TotalPrice - ReceivedDiscount);
            }

        }

        function ReloadAjaxCallbackgoback(data, successInfo) {
            CommonAjaxCallback(data, function () {
                window.location.reload();
            }, successInfo);
        }
        var toFloat = function (value) {
            value = Math.round(parseFloat(value) * 100) / 100;
            if (value.toString().indexOf(".") < 0) {
                value = value.toString() + ".00";
            }
            return value;
        }
    </script>
}


